<?php
/**
 * Mailview
 * http://code.google.com/p/mailview/
 * Martin Tournoij <martin@arp242.net>
 * Mailview is free for any use, there are no restrictions.
 */

include('mailview2.php');
include('contrib/swiftmailer/lib/swift_required.php');

$mailview = new Mailview2();

$link = Mailview\imap_open($_SESSION['config']);

$vars = array(
);

if (!isset($_POST['headers']) or !isset($_POST['body']))
{
	header('Location: index.php');
	exit(0);
}

$from = \Mailview\ParseAddress($_POST['from']);
$to = \Mailview\ParseAddress($_POST['to']);

$message = Swift_Message::newInstance()
	->setSubject($_POST['subject'])
	->setFrom($from)
	->setTo($to)
	->setBody($_POST['body'])
;

if (isset($_POST['cc']) and trim($_POST['cc']) != '')
{
	$cc = \Mailview\ParseAddress($_POST['cc']);
	$message->setCc($cc);
}

if (isset($_POST['bcc']) and trim($_POST['bcc']) != '')
{
	$bcc = \Mailview\ParseAddress($_POST['bcc']);
	$message->setBcc($bcc);
}

# Custom headers
if (isset($_POST['headers']) and trim($_POST['headers']) != '')
{
	$headers = explode("\n", $_POST['headers']);

	foreach ($headers as $h)
	{
		$h = explode(':', $h);
		if (isset($h['0']) && isset($h['1']))
			$message->getHeaders()->addTextHeader(trim($h['0']), trim($h['1']));
	}
}

# Sendmail binary
if ($_SESSION['config']['smtpserver'] === 'sendmail')
{
	# XXX Make binary an option
	$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
}
# mail()
elseif ($_SESSION['config']['smtpserver'] === 'mail')
{
	$transport = Swift_MailTransport::newInstance();
}
# SMTP connection
else
{
	$server = explode(':', $_SESSION['config']['smtpserver']);
	$transport = Swift_SmtpTransport::newInstance(trim($server['1'], ' /'), (int) $server['2']);

	if ($server['0'] === 'smtps')
	{
		if ($_SESSION['config']['smtptls'] === 1)
			$transport->setEncryption('tls');
		else
			$transport->setEncryption('ssl');
	}

	if ($_SESSION['config']['smtpauth'] === 1)
	{
		$_SESSION['config']['smtpusername'] = str_replace('$username',
			$_SESSION['config']['username'], $_SESSION['config']['smtpusername']);
		$_SESSION['config']['smtppassword'] = str_replace('$password',
			$_SESSION['config']['password'], $_SESSION['config']['smtppassword']);
			
		$transport->setUsername($_SESSION['config']['smtpusername']);
		$transport->setPassword($_SESSION['config']['smtppassword']);
	}
}

$mailer = Swift_Mailer::newInstance($transport);
$vars['numsent'] = $mailer->send($message, $vars['fail']);

$mailview->Template($vars, $link);
?>
